<?php
//error_reporting(0);
//session_start();

include(dirname(__DIR__).'/includes/db_conn_new.inc'); 

function checkUser($username,$password){ 
		
	//$query = "select * from crm_logininfo where email_address='".$username."' and password = '".md5($password)."'";    
	$query = "SELECT * FROM `client_logininfo` l 
				JOIN `crm_contact` c ON c.Email = l.email_address 
				WHERE l.email_address = '".$username."' AND l.password = '".md5($password)."' AND c.Sacc_accountlock <> '1';";
	echo $query; //exit;
	$res = mysql_query($query);
	$num_rows = mysql_num_rows($res);
	if($num_rows > 0)
	{
		while($row = mysql_fetch_array($res))
		{
			echo '<pre>'; print_r($row); exit;
			$sqlRes = mysql_query("SELECT app_id FROM crm_applicationcontact WHERE ContactID = ".$row['OriginalContact_id']." ORDER BY ApplicationcontactID DESC LIMIT 1");
			$resData = mysql_fetch_assoc($sqlRes);
			$_SESSION['display_name'] = $row['display_name'];
			$_SESSION['app_email_addr'] = $row['email_address'];
			$_SESSION['applicant_id'] = $row['OriginalContact_id'];
			$_SESSION['CurrentContact_id'] = $row['CurrentContact_id'];			
			$_SESSION['app_id'] = $resData['app_id'];
		}    
		saveLoginHistory();
		return true;
	}
	else
	{
		return false;
	}
	
	
}

/*function displaycontact ($ContactID){
	$sql = mysql_query("SELECT app_id FROM crm_contact WHERE ContactID = ".$row['OriginalContact_id']." ORDER BY CreatedDate DESC LIMIT 1");
$resData = mysql_fetch_assoc($sql);
$_SESSION['display_name'] = $row['FirstName'];
$_SESSION['app_email_addr'] = $row['Email'];
$_SESSION['addresss'] = $row['address'];
$_SESSION['telephone'] = $row['Mobile'];
$result = mysql_query($sql); 
    return mysql_fetch_array($result);
}*/
	


function saveActivityHistory($action, $description)
{
	$sql = "INSERT INTO crm_history (`app_id`,`OriginalContact_id`,`HistoryDate`,`HistoryTime`,`Action`,`Operator`,`Description`) VALUES('".$_SESSION['app_id']."', '".$_SESSION['applicant_id']."', '".date('Y-m-d')."', '".date('H:s:i')."', '".$action."', '".$_SESSION['display_name']."', '".$description."')";
	mysql_query($sql);
}

function saveLoginHistory()
{
	$login_history_query = "INSERT INTO `client_loginhistory` (`loginhistoryID`,`CurrentContact_id`,`OriginalContact_id`,`display_name`,`email_address`,`LoginDate`, `LoginTime`, `LoginIP`, `LoginBrowser`, `Comesfrom`) VALUES ('NULL', '".$_SESSION['CurrentContact_id']."', '".$_SESSION['applicant_id']."', '".$_SESSION['display_name']."', '".$_SESSION['app_email_addr']."', '".date('Y-m-d')."', '".date('H:s:i')."', '".$_SERVER['REMOTE_ADDR']."', '".$_SERVER['HTTP_USER_AGENT']."', 'MC');";
	if(!mysql_query($login_history_query));
		echo mysql_error();
}

function checkLoanNodays($userid)
{
	$loanCheck = "SELECT DATEDIFF( CURDATE( ) , ca.CreatedDate ) AS no_days, cac.app_id, ca.CreatedDate, ca.status
				FROM  `crm_applicationcontact` cac
				JOIN client_logininfo cl ON cl.OriginalContact_id = cac.ContactID
				JOIN crm_application ca ON ca.app_id = cac.app_id
				WHERE cl.OriginalContact_id = ".$userid." AND ca.status != 'close' 
				ORDER BY ca.CreatedDate DESC 
				LIMIT 1";
	//echo $loanCheck; exit;
	$res = mysql_query($loanCheck);
	
	if($num = mysql_num_rows($res))
	
	if(isset($num) && $num > 0)	
		return mysql_fetch_array($res);
	else
		return 0;
}

function displayLoanContract($app_id){
	$loanContract="select cl.LoanAmount,cl.firstPaymentDate,cl.RepaymentBy,cl.CreatedDate,cl.FilePath,cl.PaymentRegular,cl.LastPaymentDate,cc.FirstName,cc.Mobile,cc.HomePhone,cc.Email,cc.StreetNo,cc.Street,cc.Suburb,cc.State,cc.PostCode from crm_loancontract cl
	JOIN crm_contact cc ON cc.ContactID = cl.ContactID where cl.app_id= ".$app_id." ORDER BY LoanContractID DESC LIMIT 1";
	$res = mysql_query($loanContract);
	$num = mysql_num_rows($res);
	$contract = mysql_fetch_assoc($res);
	if(isset($num) && $num > 0)	{
		return $contract;
	}else{
		return false;   
	}
	
		
}

function getApplication($app_id)
{
	$loan_app = "SELECT * FROM crm_application WHERE app_id = ".$app_id;
	$res = mysql_query($loan_app);
	$num = mysql_num_rows($res);
	$applicarion = mysql_fetch_assoc($res);
	if(isset($num) && $num > 0)	{
		return $applicarion;
	}else{
		return false;  
	}
}



/*function displayLoanContract($app_id){
	$loanContract="select FilePath from crm_loancontract where app_id= ".$app_id." ORDER BY LoanContractID DESC LIMIT 1";
	$res = mysql_query($loanContract);
	$num = mysql_num_rows($res);
	$contract = mysql_fetch_assoc($res);
	if(isset($num) && $num > 0)	{
		return $contract['FilePath'];
	}else{
		return false;  
	}
	
		
}*/

function getMCFileUrl()
{
	$req_type = $_SERVER['REQUEST_SCHEME'];
	$server = $_SERVER['HTTP_HOST'];
	$url = $req_type.'://www.'.$server;
	
	if($_SERVER['SERVER_NAME'] == 'localhost')
	{
		$url = $req_type.'://'.$server;
	}
	$root = explode('/',$_SERVER['PHP_SELF']);
	if(in_array('account', $root))
	{
		$flag = true;
		foreach($root as $str)
		{
			if($str == 'account')
			{
				$flag = false;
			}
			
			if($flag)
			{
				$url .= $str.'/';
			}
		}
	}
	return $url;
}

function getLoanStatus($app_id){
	

	$sql = "SELECT status, MC_Process FROM crm_application WHERE app_id =".$app_id." ORDER BY CreatedDate DESC LIMIT 1"; 
    $result = mysql_query($sql); 
    return mysql_fetch_array($result);

}

function getContractstatus($app_id){ 
	
	$sql = "SELECT contractprepared, contractsigned FROM sacc_verificationstatus WHERE app_id =".$app_id." ORDER BY CreatedDate DESC LIMIT 1";	
	$result = mysql_query($sql);  	
    return mysql_fetch_array($result);	
}

function isConfirm($app_id) 
{
	$sql = "SELECT count(*) AS verifyStatus FROM sacc_verificationstatus WHERE idcheck_status = 1 AND payslip_status = 1 AND bankretrieve_status = 1 AND app_id = ".$app_id;
	$res = mysql_query($sql);
	$resSet = mysql_fetch_array($res); 
	
	if($resSet['verifyStatus'] > 0)
	{
		mysql_query("UPDATE crm_application SET MC_Process = 'confirm' WHERE app_id = ".$app_id);		
	}	
}

function getVerificationStatus($app_id)
{
	$sql = "SELECT * FROM sacc_verificationstatus WHERE app_id = '".$app_id."' ORDER BY CreatedDate DESC LIMIT 1;";
	$row = '';	
	if($res = mysql_query($sql)) 
	$num = mysql_num_rows($res);
	if($num > 0)
	{
		$row = mysql_fetch_array($res, MYSQLI_ASSOC);	
	}	
	else
	{
		$row = NULL;
	}
	return $row;
}

function sentEmail($to, $msg, $sub)
{
	//$subject = 'Application Form technical error report';
	//$to = 'MFtesting1234@hotmail.com';
	$to1="cashlogin@gmail.com";
	//$to = 'infaario@gmail.com';
	$message = $msg;
	$subject = $sub;	
	if($msg){
		
		$headers  = 'MIME-Version: 1.0' . "\r\n";
		$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
		$headers .= 'From: Email Verification<alert@Max Cash.com.au> ' . "\r\n";
		$headers .= 'Cc: cashlogin@gmail.com, development6600@gmail.com' . "\r\n";    		
		//$send_contact =  mail($to,$subject,$message,$headers,"-f contact@Max Cash.com.au"); 
		$send_contact =  mail($to,$subject,$message,$headers); 
		if($send_contact)
		{
			return true;				
		}
		else
		{
			return false;
		} 			
	}
}

function sendSMS($mobile, $pin_code)
{
	require("../includes/sms/smsconn.php");
	$monumber = $mobile;
	//$pin_code = generatePassword($length = 8);
	$smscontent = "Verify SMS: For verification purposes please use this pin code ".$pin_code.". Morgan Finance";
	/*$si = new SmsInterface();
	$si->addMessage($monumber,$smscontent);
	
	if (!$si->connect($username,$password,true,false)){
		$sms_emsg = "failed. Could not contact sms server.\n";
	}
	elseif (!$si->sendMessages()) {
		$sms_emsg = "failed. Could not send message to server.\n";
		if ($si->getResponseMessage() !== NULL)
			$sms_emsg = "<br/>Reason: " . $si->getResponseMessage() . "\n";
	}
	else
	{
		$sms_emsg = true;
	}*/
	
	
	$si = new SmsInterface (false, false);
	$si->addMessage ($mobile, $smscontent);

	if (!$si->connect ($username, $password, true, false))
	    $sms_emsg = "failed. Could not contact server.\n";
	elseif (!$si->sendMessages ()) 
	{
	    $sms_emsg = "failed. Could not send message to server.\n";
	    if ($si->getResponseMessage () !== NULL)
			$sms_emsg = "<BR>Reason: " . $si->getResponseMessage () . "\n";
	} 
	else
	    $sms_emsg = true;
	
	//return $si->getResponseMessage();
	return $sms_emsg;
}

function getmobileno($ContactID)
{
	$sql = "SELECT Mobile FROM crm_contact WHERE ContactID =".$ContactID." ";
    $result = mysql_query($sql); 
	$mobileNo = mysql_fetch_array($result);	
	return $mobileNo['Mobile'];
}

function getDateFormat($timestamp, $format)
{
	date_default_timezone_set('Asia/Kolkata'); 
	if($format == 'YmdHsi')
	{
		return date("Ymdgis", $timestamp);//date('YmdHsi', $timestamp);
	}
	else if($format == '')
	{
		return date('Y-m-d g:i:s', $timestamp);
	}
}


function mysql_update($tbl_name, $arr_data, $where_condition)
{
	$inc = 1;
	$sql = "UPDATE ".$tbl_name." SET ";
	if(is_array($arr_data) and $arr_data != NULL)
	{
		foreach($arr_data as $tbl_column => $tbl_column_value)
		{
			$sql .= "`".$tbl_column."` = '".$tbl_column_value."',";
		}
		$sql = substr($sql, 0, -1);
				
		foreach($where_condition as $tbl_primary_key => $tbl_primary_key_value)
		{
			if($inc == 1)
			{
				$key_value = "`".$tbl_primary_key."` = '".$tbl_primary_key_value."'";
			}
			else
			{
				$key_value .= " and `".$tbl_primary_key."` = '".$tbl_primary_key_value."'";
			}
			$inc++;
		}
		$sql .= " WHERE ".$key_value.";";
		/*if(count($where_condition) > 1)
		{
			$inc = 1;
			foreach($where_condition as $tbl_primary_key => $tbl_primary_key_value)
			{
				if($inc == 1)
				{
					$key_value = "`".$tbl_primary_key."` = '".$tbl_primary_key_value."'";
				}
				else
				{
					$key_value = " and `".$tbl_primary_key."` = '".$tbl_primary_key_value."'";
				}
				$inc++;
			}
		}
		else
		{
			foreach($where_condition as $tbl_primary_key => $tbl_primary_key_value)
			{
				$key_value = "`".$tbl_primary_key."` = '".$tbl_primary_key_value."'";
			}
		}*/
		
		
		
	}
	//echo $sql;
	if(!mysql_query($sql))
		return mysql_error();
	else
		return 1;
}

function mysql_insert($tbl_name, $arr_data)
{
	$sql = "INSERT INTO ".$tbl_name." SET ";
	if(is_array($arr_data) and $arr_data != NULL)
	{
		foreach($arr_data as $tbl_column => $tbl_column_value)
		{
			if($tbl_column_value == 'CURRENT_TIMESTAMP')
				$sql .= "`".$tbl_column."` = ".$tbl_column_value.",";
			else
				$sql .= "`".$tbl_column."` = '".$tbl_column_value."',";
		}
		$sql = substr($sql, 0, -1);		
	}
	
	if(!mysql_query($sql))
		return mysql_error();
	else 
		return mysql_insert_id();
}

function generatePassword($length) {
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $count = mb_strlen($chars);

    for ($i = 0, $result = ''; $i < $length; $i++) {
        $index = rand(0, $count - 1);
        $result .= mb_substr($chars, $index, 1);
    }

    return $result;
}

function encrypt_decrypt($action, $string) {
   $output = false;

   $key = '!@1';

   // initialization vector 
   $iv = md5(md5($key));

   if( $action == 'encrypt' ) {
       $output = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, $iv);
       $output = base64_encode($output);
   }
   else if( $action == 'decrypt' ){
       $output = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($string), MCRYPT_MODE_CBC, $iv);
       $output = rtrim($output, "");
   }
   //return $output;
   
   echo $output;
}

function encrypt($string, $key) { 
$result = ''; 
for($i=0; $i<strlen($string); $i++) { 
$char = substr($string, $i, 1); 
$keychar = substr($key, ($i % strlen($key))-1, 1); 
$char = chr(ord($char)+ord($keychar)); 
$result.=$char; 
}

return base64_encode($result); 
}

function decrypt($string, $key) { 
$result = ''; 
$string = base64_decode($string);

for($i=0; $i<strlen($string); $i++) { 
$char = substr($string, $i, 1); 
$keychar = substr($key, ($i % strlen($key))-1, 1); 
$char = chr(ord($char)-ord($keychar)); 
$result.=$char; 
}

return $result; 
}


function mail_attachment($filename, $path, $from_mail, $subject, $message) {
	$mailto = "Loans@maxcash.com.au";
	//$mailto = "infaario@gmail.com";
    $file = $path.$filename;
    $file_size = filesize($file);
    $handle = fopen($file, "r");
    $content = fread($handle, $file_size);
    fclose($handle);
    $content = chunk_split(base64_encode($content));
    $uid = md5(uniqid(time()));
    $name = basename($file);
    $header = "From: ".$from_name." <".$from_mail.">\r\n";
    $header .= "Reply-To: ".$replyto."\r\n";
    $header .= "MIME-Version: 1.0\r\n";
    $header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
    $header .= "This is a multi-part message in MIME format.\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
    $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
    $header .= $message."\r\n\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use different content types here
    $header .= "Content-Transfer-Encoding: base64\r\n";
    $header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
    $header .= $content."\r\n\r\n";
    $header .= "--".$uid."--";
    if (mail($mailto, $subject, "", $header)) {
        return true;
    } else {
        return false;
    }
}

function mail_multi_attachment($files, $from_mail, $mailto, $subject, $message, $cc = NULL) {
	
$from_name = $_SESSION['display_name'];	
//$headers = "From: ".$from_name." <".$from_mail.">\r\n";
$headers = "From: $from_mail"; 
// boundary 
$semi_rand = md5(time()); 
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; 
 
// headers for attachment 
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; 
 
// multipart boundary 
$message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n"; 
$message .= "--{$mime_boundary}\n";
 
// preparing attachments
for($x=0;$x<count($files);$x++){
    $file = fopen($files[$x],"rb");
    $data = fread($file,filesize($files[$x]));
    fclose($file);
    $data = chunk_split(base64_encode($data));
    $message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" . 
    "Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" . 
    "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
    $message .= "--{$mime_boundary}\n";
}
 
// send
 
$ok = mail($mailto, $subject, $message, $headers); 
return $ok;
/*if (mail($mailto, $subject, $message, $headers)) {
        return true;
    } else {
        return false;
    }*/
}


?>